import { Hono } from 'hono'
import { z } from 'zod'
import { ApiKeyService } from '@/services/apiKeyService'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'

const apiKeys = new Hono()
const apiKeyService = new ApiKeyService()

// 验证模式
const createApiKeySchema = z.object({
  name: z.string().min(3).max(100),
  permissions: z.array(z.string()).optional(),
  rateLimitPerHour: z.number().min(1).max(10000).optional(),
  expiresAt: z.string().datetime().optional().transform(val => val ? new Date(val) : undefined)
})

const updateApiKeySchema = z.object({
  name: z.string().min(3).max(100).optional(),
  permissions: z.array(z.string()).optional(),
  rateLimitPerHour: z.number().min(1).max(10000).optional(),
  expiresAt: z.string().datetime().optional().transform(val => val ? new Date(val) : undefined)
})

// 验证中间件
const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError('Invalid input data', error.errors)
      }
      throw error
    }
  }
}

// 导入认证中间件
import { getCurrentUser } from '@/middleware/auth'

// 获取当前用户ID的辅助函数
const getCurrentUserId = (c: any): string => {
  const user = getCurrentUser(c)
  if (!user) {
    throw new ValidationError('User not authenticated')
  }
  return user.sub
}

// 获取API密钥列表
apiKeys.get('/',
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)
    const apiKeys = await apiKeyService.getApiKeys(userId)

    return c.json({
      success: true,
      data: { apiKeys },
      message: 'API keys retrieved successfully'
    })
  })
)

// 创建新的API密钥
apiKeys.post('/',
  validateJson(createApiKeySchema),
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)
    const data = c.get('validatedData')

    const result = await apiKeyService.createApiKey(userId, data)

    return c.json({
      success: true,
      data: result,
      message: 'API key created successfully'
    }, 201)
  })
)

// 获取API密钥详情
apiKeys.get('/:id',
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)
    const keyId = c.req.param('id')

    const apiKey = await apiKeyService.getApiKey(userId, keyId)

    return c.json({
      success: true,
      data: { apiKey },
      message: 'API key retrieved successfully'
    })
  })
)

// 更新API密钥
apiKeys.put('/:id',
  validateJson(updateApiKeySchema),
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)
    const keyId = c.req.param('id')
    const data = c.get('validatedData')

    const apiKey = await apiKeyService.updateApiKey(userId, keyId, data)

    return c.json({
      success: true,
      data: { apiKey },
      message: 'API key updated successfully'
    })
  })
)

// 删除API密钥
apiKeys.delete('/:id',
  asyncHandler(async (c) => {
    const userId = getCurrentUserId(c)
    const keyId = c.req.param('id')

    await apiKeyService.deleteApiKey(userId, keyId)

    return c.json({
      success: true,
      message: 'API key deleted successfully'
    })
  })
)

export default apiKeys
